import 'dart:async';
import 'dart:convert';
import 'dart:convert' as convert;
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/config/_.dart';

class IndexSearch extends StatefulWidget {
  final int searchStatus;
  IndexSearch({required this.searchStatus});
  @override
  _IndexSearch createState() =>
      _IndexSearch(searchStatus: searchStatus);
}

class _IndexSearch extends State<IndexSearch> {
  int searchStatus;
  late List<SearchRecommendEntity> searchRecommendList;
  late TextEditingController _controller;
  List<String> historyList = [];
  late Future<dynamic> _function;
  bool historyStatus = false;

  _IndexSearch({required this.searchStatus});
  @override
  void initState() {
    super.initState();
    getHistory();
    _controller = TextEditingController(text: "");
    _function = future();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        elevation: 2,
        toolbarHeight: Screen.setHeight(60),
        backgroundColor: ColorConfig.ThemeColor,
        automaticallyImplyLeading: false,
        titleSpacing: 0,
        title: search(),
      ),
      backgroundColor: ColorConfig.WhiteBackColor,
      body: FutureBuilder(
        future: _function,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          return snapshot.connectionState == ConnectionState.done
              ? GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Container(
              height: Screen.height(context) -
                  Screen.setHeight(60) -
                  Config.top,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: SearchRecommendWidget(
                      searchRecommendList: searchRecommendList,
                      title: searchStateValue[searchStatus]["TopicValue"],
                      clickTopicItem: (String e) {
                        FocusScope.of(context).requestFocus(FocusNode());
                        Modular.to.pushNamed(
                            "/indexResultsList/$e/$searchStatus");
                        Timer(Duration(milliseconds: 280), (){
                          setState(() {
                            _controller.text = e;
                          });
                          if (searchStatus == 0) setHistory(e);
                        });


                      },
                    ),
                  ),
                  Visibility(
                    visible:
                    this.searchStatus == 0 && historyList.length != 0,
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          Container(
                            constraints: this.historyStatus?BoxConstraints(
                                minHeight:140
                            ):BoxConstraints(
                                maxHeight:140
                            ),
                            child: titleSection(
                                "历史搜索",
                                Wrap(
                                  runSpacing: 7,
                                  spacing: 7,
                                  children: [
                                    ...historyList
                                        .asMap()
                                        .keys
                                        .map(
                                          (e) => GestureDetector(
                                        onTap: () {
                                          String res = historyList[e];
                                          FocusScope.of(context)
                                              .requestFocus(
                                              FocusNode());
                                          Modular.to.pushNamed(
                                            "/indexResultsList/$res/0",
                                          );
                                          Timer(Duration(milliseconds: 280), (){
                                            setState(() {
                                              _controller.text = res;
                                            });
                                            setHistory(res);
                                          });


                                        },
                                        child: ClipRRect(
                                          borderRadius:
                                          BorderRadius.all(
                                              Radius.circular(5)),
                                          child: Container(
                                            constraints:
                                            BoxConstraints(
                                                minHeight: 30,
                                                maxWidth: 100),
                                            decoration: BoxDecoration(
                                              color: ColorConfig
                                                  .LineColor,
                                            ),
                                            padding:
                                            EdgeInsets.all(5),
                                            child: Text(
                                              historyList[e],
                                              overflow: TextOverflow
                                                  .ellipsis,
                                              textAlign:
                                              TextAlign.center,
                                              style: TextStyle(
                                                  color: ColorConfig
                                                      .BlackBackColor,
                                                  fontSize: 13),
                                            ),
                                          ),
                                        ),
                                      ),
                                    )
                                        .toList(),
                                  ],
                                )),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          GestureDetector(
                            onTap: ()async{
                              await SPreferences().deleteData("historyList");
                              historyList=[];
                              setState(() {
                              });
                              BotToast.showText(text: '清除成功');
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.delete,
                                  color: ColorConfig.TextColor,
                                ),
                                SizedBox(
                                  width: 4,
                                ),
                                Text(
                                  '清空搜索历史',
                                  style: TextStyle(
                                      color: ColorConfig.TextColor
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                  ,
                ],
              ),
            ),
          )
              : Loading();
        },
      ),
    );
  }

  future() async {
    await getSearchRecommend();
  }

  Future<void> getSearchRecommend() async {
    searchRecommendList = (await SearchService.getSearchRecommend(
        params: {"search_Type": searchStatus}))!;
  }

  Widget search() {
    return Panel(
      top: 0,
      bottom: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
              child: Container(
            width: Screen.width(context),
            height: Screen.setHeight(40),
            decoration: BoxDecoration(
              color: ColorConfig.WhiteBackColor,
              borderRadius: BorderRadius.all(Radius.circular(28.0)),
            ),
            child: TextField(
              maxLength: 50,
              showCursor: true,
              cursorWidth: 2,
              cursorRadius: Radius.circular(10),
              cursorColor: Colors.red,
              controller: _controller,
              textInputAction: TextInputAction.search,
              onSubmitted: (res) {
                if (_controller.text == '') return;
                Modular.to.pushNamed("/indexResultsList/$res/$searchStatus");
                Timer(Duration(milliseconds: 280), (){
                  setHistory(res);
                });
              },
              decoration: InputDecoration(
                counterText: '',
                isDense: true,
                hintText: searchStateValue[searchStatus]["searchValue"],
                hintStyle: TextStyle(color: ColorConfig.TextColor),
                hintMaxLines: 1,
                prefixIcon: Icon(
                  Icons.search,
                  color: ColorConfig.TextColor,
                  size: 20,
                ),
                enabledBorder: UnderlineInputBorder(
                  //选中时下边框颜色
                  borderSide: BorderSide(color: ColorConfig.ThemeColor),
                ),
                focusedBorder: UnderlineInputBorder(
                  //选中时下边框颜色
                  borderSide: BorderSide(color: ColorConfig.ThemeColor),
                ),
              ),
            ),
          )),
          IconButton(
            onPressed: () {
              Modular.to.pop();
            },
            icon: Icon(Icons.clear),
          )
        ],
      ),
    );
  }

  Widget titleSection(String title, Widget child) {
    return Panel(
      top: 0,
      bottom: 10,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: Container(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: Text(
                    title,
                    style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
                  ),
                )),
                TextButton(
                  onPressed: (){
                    this.historyStatus = !this.historyStatus;
                    setState(() {

                    });
                  },
                    style: ButtonStyle(
                      overlayColor: MaterialStateProperty.all(
                        ColorConfig.WhiteBackColor
                      )
                    ),
                    child: Text(
                      this.historyStatus?'收起':'展开',
                      style: TextStyle(
                          height: 0.5,
                          color: ColorConfig.TextColor,fontSize: 13
                      ),
                    ) ,
                )

              ],
            ),
            SizedBox(
              height: 10,
            ),
            child,
          ],
        ),
      ),
    );
  }

  setHistory(String value) {
    int index = historyList.indexOf(value);
    if (index == -1) {
      setHistoryList(value);
      return;
    }
    historyList.remove(value);
    setHistoryList(value);
  }

  getHistory() {
    String res = SPreferences().getString("historyList");
    if (res != '') {
      List<String> res =
          jsonDecode(SPreferences().getString("historyList")).cast<String>();
      historyList = res;
    }
  }

  setHistoryList(String value) {
    historyList = [value, ...historyList];
    SPreferences().setString("historyList", convert.jsonEncode(historyList));
    setState(() {});
  }
}

List<Map<String, dynamic>> searchStateValue = [
  {"searchValue": '精彩从这里开始', "TopicValue": '热搜'},
  {"searchValue": '搜索热门动态', "TopicValue": '大家都在搜'},
  {"searchValue": '搜索话题', "TopicValue": '热门话题集选'}
];
